import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_neumorphic_plus/flutter_neumorphic.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:psi/theme/app_colors.dart';
import 'package:psi/widgets/gesture.dart';
import 'package:psi/widgets/text_widget.dart';

import '../generated/assets.dart';

class WidgetUtil {
  WidgetUtil._();

  static Widget assetImage(
    String imgName, {
    double? width,
    double? height,
    BoxFit boxFit = BoxFit.cover,
    double? size,
    Color? color,
  }) {
    return Image.asset(
      imgName,
      width: size != null ? size : width,
      height: size != null ? size : height,
      fit: boxFit,
      color: color,
    );
  }

  static const Widget divider = Divider(
    thickness: 1,
    height: 1,
    color: Color(0xFFF5F6F7),
  );

  static const Widget verticalDivider = VerticalDivider(
    thickness: 1,
    width: 1,
    color: Color(0xFFF5F6F7),
  );

  static Widget getCardItem(
      {required Widget child,
      EdgeInsets padding = const EdgeInsets.all(16),
      Color color = Colors.white,
      double depth = 10,
      double intensity = 0.5,
      NeumorphicShape shape = NeumorphicShape.flat,
      double surfaceIntensity = 0.25,
      BorderRadius? radius,
      VoidCallback? onTap}) {
    if (radius == null) {
      radius = BorderRadius.circular(8);
    }
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: onTap,
      child: Neumorphic(
        padding: padding,
        style: NeumorphicStyle(
          depth: depth,
          intensity: intensity,
          shape: shape,
          color: color,
          surfaceIntensity: surfaceIntensity,
          boxShape: NeumorphicBoxShape.roundRect(radius),
        ),
        child: child,
      ),
    );
  }

  static Widget getInnerCardItem(
      {required Widget child,
      EdgeInsets padding = const EdgeInsets.all(16),
      Color color = Colors.white,
      double depth = -5,
      double intensity = 1,
      NeumorphicShape shape = NeumorphicShape.flat,
      double surfaceIntensity = 0.25,
      BorderRadius? radius,
      VoidCallback? onTap}) {
    if (radius == null) {
      radius = BorderRadius.circular(8.w);
    }
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: onTap,
      child: Neumorphic(
        padding: padding,
        style: NeumorphicStyle(
          depth: depth,
          intensity: intensity,
          shape: shape,
          color: color,
          surfaceIntensity: surfaceIntensity,
          boxShape: NeumorphicBoxShape.roundRect(radius),
          shadowDarkColorEmboss: Color(0xFFDDDDDD),
        ),
        child: child,
      ),
    );
  }

  static Widget imageBtn({
    required String imageName,
    double? width,
    double? height,
    BoxFit boxFit = BoxFit.cover,
    double? size,
    Color? color,
    EdgeInsets? padding,
    VoidCallback? onTap,
  }) {
    return ClickWidget(
      onTap: onTap,
      child: Container(
        padding: padding,
        child: WidgetUtil.assetImage(imageName, width: width, height: height, size: size, boxFit: boxFit),
      ),
    );
  }

  static Widget inputWidget(
      {double? width,
      double? height,
      String? value,
      ValueChanged? onChanged,
      VoidCallback? onComplete,
      String? placeHolder,
      bool obscureText = false,
      TextInputType? inputType = TextInputType.text,
      bool showClean = true,
        bool canEdit = true,
      bool showReal = false}) {
    TextEditingController editingController = TextEditingController(text: value);
    bool showClean = false;
    return StatefulBuilder(builder: (ctx, setState) {
      return Neumorphic(
        style: const NeumorphicStyle(
          depth: -5,
          intensity: 1,
          color: Colors.white,
          shadowDarkColorEmboss: Color(0xFFDDDDDD),
        ),
        child: Container(
          height: height,
          padding: EdgeInsets.symmetric(horizontal: 8.w),
          child: Row(
            children: [
              Expanded(
                child: TextField(
                  controller: editingController,
                  keyboardType: inputType,
                  style: TextWidget.createTextStyle(fontSize: 14, color: primaryColor),
                  obscureText: obscureText,
                  readOnly: !canEdit,
                  decoration: InputDecoration(
                    hintText: placeHolder ??= "请输入",
                    hintStyle: TextWidget.createTextStyle(fontSize: 14, color: Color(0xFF999999)),
                    hintMaxLines: 1,
                    contentPadding: const EdgeInsets.all(0),
                    enabledBorder: const OutlineInputBorder(borderSide: BorderSide(color: Colors.transparent), borderRadius: BorderRadius.zero),
                    focusedBorder: const OutlineInputBorder(borderSide: BorderSide(color: Colors.transparent), borderRadius: BorderRadius.zero),
                  ),
                  onChanged: (text) {
                    if (showClean != text.isNotEmpty) {
                      setState(() {
                        showClean = text.isNotEmpty;
                      });
                    }
                    if (onChanged != null) {
                      String value = text.trim();
                      onChanged(value);
                    }
                  },
                  onEditingComplete: onComplete,
                ),
              ),
              if (showClean)
                Row(
                  children: [
                    16.horizontalSpace,
                    WidgetUtil.imageBtn(
                        imageName: R.iconClean,
                        size: 16,
                        onTap: () {
                          editingController.clear();
                        })
                  ],
                ),
              if (showReal)
                Row(
                  children: [
                    16.horizontalSpace,
                    WidgetUtil.imageBtn(
                        imageName: obscureText ? R.eyeOn : R.eyeOff,
                        size: 20,
                        onTap: () {
                          setState(() {
                            obscureText = !obscureText;
                          });
                        })
                  ],
                ),
            ],
          ),
        ),
      );
    });
  }

  static void showAlert({
    String title = '',
    required String message,
    String cancelTitle = '取消',
    VoidCallback? onCancel,
    String doneTitle = '确认',
    VoidCallback? onDone,
  }) {
    showCupertinoDialog(
        context: Get.context!,
        builder: (context) {
          return CupertinoAlertDialog(
            title: (title != null && title.isNotEmpty)
                ? TextWidget(
                    title,
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Colors.black,
                    textAlign: TextAlign.center,
                  )
                : null,
            content: (message != null && message.isNotEmpty) ? TextWidget(message, fontSize: 14, textAlign: TextAlign.center) : null,
            actions: <Widget>[
              CupertinoDialogAction(
                child: TextWidget(
                  cancelTitle,
                  color: Color(0xFFFF0505),
                  fontWeight: FontWeight.w600,
                  fontSize: 15,
                ),
                onPressed: () {
                  Get.back();
                  if (onCancel != null) {
                    onCancel();
                  }
                },
              ),
              CupertinoDialogAction(
                child: TextWidget(
                  doneTitle,
                  color: Color(0xFF3E8BF8),
                  fontWeight: FontWeight.w600,
                  fontSize: 15,
                ),
                onPressed: () {
                  Get.back();
                  if (onDone != null) {
                    onDone();
                  }
                },
              ),
            ],
          );
        });
  }

  static void showDatePicker(
      {String title = '',
      CupertinoDatePickerMode mode = CupertinoDatePickerMode.date,
      DateTime? initDate,
      String cancelTitle = '取消',
      String doneTitle = '确定',
      ValueChanged? selectCallback,
      ValueChanged? doneCallback}) {
    DateTime tempDate = initDate ?? DateTime.now();
    showModalBottomSheet(
        context: Get.context!,
        backgroundColor: Colors.white,
        elevation: 10,
        builder: (BuildContext context) {
          return SafeArea(
            child: Container(
              height: ScreenUtil().screenHeight / 3,
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: <Widget>[
                      Spacer(),
                      ClickWidget(
                        onTap: () {
                          Navigator.of(context).pop();
                        },
                        child: Container(
                            padding: EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                            child: TextWidget(
                              cancelTitle,
                              color: primaryColor,
                              fontSize: 18,
                            )),
                      ),
                      const Spacer(
                        flex: 6,
                      ),
                      TextWidget(title, fontSize: 20, fontWeight: FontWeight.w600),
                      const Spacer(
                        flex: 6,
                      ),
                      ClickWidget(
                        onTap: () {
                          Navigator.of(context).pop();
                          if (doneCallback != null) {
                            doneCallback(tempDate);
                          }
                        },
                        child: Container(
                            padding: EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                            child: TextWidget(
                              doneTitle,
                              color: primaryColor,
                              fontSize: 18,
                            )),
                      ),
                      Spacer(),
                    ],
                  ),
                  Expanded(
                    child: CupertinoDatePicker(
                      mode: mode,
                      initialDateTime: initDate ?? DateTime.now(),
                      maximumDate: DateTime.now(),
                      onDateTimeChanged: (date) {
                        tempDate = date;
                      },
                    ),
                  )
                ],
              ),
            ),
          );
        });
  }

  static void showPicker(
      {String title = '', required List dataSource, int selectedIndex = 0, String cancelTitle = '取消', String doneTitle = '确定', ValueChanged? selectCallback, ValueChanged? doneCallback}) {
    FixedExtentScrollController scrollController = FixedExtentScrollController(initialItem: selectedIndex);
    showModalBottomSheet(
        context: Get.context!,
        backgroundColor: Colors.white,
        elevation: 10,
        builder: (BuildContext context) {
          return SafeArea(
            child: Container(
              height: ScreenUtil().screenHeight / 3,
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      Spacer(),
                      ClickWidget(
                        onTap: () {
                          Navigator.of(context).pop();
                        },
                        child: Container(
                            padding: EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                            child: TextWidget(
                              cancelTitle,
                              color: primaryColor,
                              fontSize: 18,
                            )),
                      ),
                      const Spacer(
                        flex: 6,
                      ),
                      TextWidget(title, fontSize: 20, fontWeight: FontWeight.w600),
                      const Spacer(
                        flex: 6,
                      ),
                      ClickWidget(
                        onTap: () {
                          Navigator.of(context).pop();
                          if (doneCallback != null) {
                            doneCallback(dataSource[selectedIndex]);
                          }
                        },
                        child: Container(
                            padding: EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                            child: TextWidget(
                              doneTitle,
                              color: primaryColor,
                              fontSize: 18,
                            )),
                      ),
                      Spacer(),
                    ],
                  ),
                  Expanded(
                      child: CupertinoPicker(
                    scrollController: scrollController,
                    itemExtent: 45,
                    onSelectedItemChanged: (index) {
                      selectedIndex = index;
                      if (selectCallback != null) {
                        selectCallback(selectedIndex);
                      }
                    },
                    children: dataSource
                        .map((e) => Container(
                              alignment: Alignment.center,
                              child: TextWidget(e, fontSize: 16),
                            ))
                        .toList(),
                  ))
                ],
              ),
            ),
          );
        });
  }

  static Widget pickTimeWidget({required String title, DateTime? value, bool canEdit = true, ValueChanged? onDone, bool showTitle = true}) {
    return Row(
      children: [
        if (showTitle)
          Container(
            width: 100,
            child: TextWidget(
              title,
              fontSize: 16,
              color: Color(0xFF333333),
              textAlign: TextAlign.left,
            ),
          ),
        Expanded(
            child: WidgetUtil.getInnerCardItem(
                padding: EdgeInsets.symmetric(horizontal: 8.w),
                onTap: canEdit ? () {
                  WidgetUtil.showDatePicker(title: "请选择$title", initDate: value, mode: CupertinoDatePickerMode.dateAndTime, doneCallback: onDone);
                } : null,
                child: Container(
                    height: 40,
                    alignment: Alignment.centerLeft,
                    child: TextWidget(
                      value == null
                          ? title
                          : DateUtil.formatDate(
                              value,
                              format: DateFormats.full,
                            ),
                      fontSize: 14,
                      color: value == null ? Color(0xFF999999) : primaryColor,
                    ))))
      ],
    );
  }

  static Widget pickWidget({required String title, String? value, required List<String> dataSource, ValueChanged? onDone, bool showTitle = true}) {
    return Row(
      children: [
        if (showTitle)
          Container(
            width: 100,
            child: TextWidget(
              title,
              fontSize: 16,
              color: Color(0xFF333333),
              textAlign: TextAlign.left,
            ),
          ),
        Expanded(
            child: WidgetUtil.getInnerCardItem(
                padding: EdgeInsets.symmetric(horizontal: 8.w),
                onTap: () {
                  WidgetUtil.showPicker(
                      dataSource: dataSource,
                      selectedIndex: value == null ? 0 : dataSource.indexOf(value),
                      doneCallback: (value) {
                        if (onDone != null) {
                          onDone(value);
                        }
                      });
                },
                child: Container(
                    height: 40,
                    alignment: Alignment.centerLeft,
                    child: TextWidget(
                      value ?? title,
                      fontSize: 14,
                      color: value == null ? Color(0xFF999999) : primaryColor,
                    ))))
      ],
    );
  }

  static Widget listViewWithSeparated({required List<Widget> children, double height = 16, Widget? separator, bool scroller = false}) {
    return MediaQuery.removePadding(
      context: Get.context!,
      removeTop: true,
      removeBottom: true,
      child: ListView.separated(
          shrinkWrap: !scroller,
          physics: scroller ? BouncingScrollPhysics() : NeverScrollableScrollPhysics(),
          itemBuilder: (ctx, index) {
            return children[index];
          },
          separatorBuilder: (ctx, index) {
            return separator ??
                SizedBox(
                  height: height,
                );
          },
          itemCount: children.length),
    );
  }

  static Future showSheet({String? title, String? message, String? cancelTitle, List<String>? items, ValueChanged? onSelect, VoidCallback? onCancel}) {
    return showCupertinoModalPopup(
        context: Get.context!,
        builder: (context) {
          return CupertinoActionSheet(
            title: (title != null && title.isNotEmpty)
                ? TextWidget(
                    title,
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w600,
                    color: Colors.black,
                    textAlign: TextAlign.center,
                  )
                : null,
            message: (message != null && message.isNotEmpty) ? TextWidget(message, fontSize: 12.sp, textAlign: TextAlign.center) : null,
            actions: items?.map((e) {
              int index = items.indexOf(e);
              return CupertinoActionSheetAction(
                child: TextWidget(
                  e,
                  color: Color(0xFF333333),
                  fontSize: 16.sp,
                ),
                onPressed: () {
                  Get.back(result: index);
                  if (onSelect != null) {
                    onSelect(index);
                  }
                },
              );
            }).toList(),
            cancelButton: CupertinoActionSheetAction(
              child: TextWidget(
                "取消",
                color: Colors.red,
                fontWeight: FontWeight.w600,
                fontSize: 15.sp,
              ),
              onPressed: () {
                Get.back();
                if (onCancel != null) {
                  onCancel();
                }
              },
            ),
          );
        });
  }

  static Widget getStatisticsItem({required String title, required String value}) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        TextWidget(
          title,
          color: Colors.white,
          fontSize: 13,
          fontWeight: FontWeight.w500,
        ),
        TextWidget(
          value,
          color: Colors.white,
          fontSize: 13,
        )
      ],
    );
  }

  static Widget itemInputWidget({required String title, String? value, TextInputType? inputType, bool canEdit = true, ValueChanged? onChange}) {
    return Row(
      children: [
        Container(
          width: 100,
          child: TextWidget(
            title,
            fontSize: 16,
            color: Color(0xFF333333),
            textAlign: TextAlign.left,
          ),
        ),
        Expanded(child: WidgetUtil.inputWidget(value: value, inputType: inputType, placeHolder: '请输入$title', canEdit: canEdit, height: 40, onChanged: onChange))
      ],
    );
  }

  static void showInputAlert({String? title, String value = "0", ValueChanged? valueChanged}) {
    showDialog(
        context: Get.context!,
        barrierDismissible: true,
        builder: (context) {
          return Dialog(
            clipBehavior: Clip.antiAlias,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            child: Container(
              color: Colors.white,
              height: 170.w,
              child: Column(crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [
                16.verticalSpace,
                if (title != null)
                  TextWidget(
                    title,
                    fontSize: 16.sp,
                  ),
                16.verticalSpace,
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: inputWidget(
                      height: 40.w,
                      value: value,
                      inputType: TextInputType.numberWithOptions(decimal: true),
                      onChanged: (text) {
                        value = text;
                      }),
                ),
                Spacer(),
                divider,
                IntrinsicHeight(
                  child: Row(
                    children: [
                      Expanded(
                        child: CupertinoDialogAction(
                          child: TextWidget(
                            "取消",
                            color: Color(0xFFFF0505),
                            fontWeight: FontWeight.w600,
                            fontSize: 15,
                          ),
                          onPressed: () {
                            Get.back();
                          },
                        ),
                      ),
                      verticalDivider,
                      Expanded(
                        child: CupertinoDialogAction(
                          child: TextWidget(
                            "确定",
                            color: Color(0xFF3E8BF8),
                            fontWeight: FontWeight.w600,
                            fontSize: 15,
                          ),
                          onPressed: () {
                            Get.back();
                            if (valueChanged != null) {
                              valueChanged(value);
                            }
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ]),
            ),
          );
        });
  }
}
